import {core, getGameObjectById, HitTestScript, TextRenderer} from "../gameengine";
import {lockPrefab, screenPrefab} from "../data/data";

export class Lock {
    public input: string;
    private password: string = "3733";
    private buttons: Button[] = [];
    public pass: Function;
    public failed: Function;
    public textRenderer: TextRenderer;
    public currentPassword: number = 0;

    //自己改密码
    private passwords:string[]=["2358","3733","1111"];

    constructor() {
        this.pass = () => {
            console.log("Correct!");
        };

        this.failed = () => {
            console.log("Failed!");
        };
    }

    public lockInstantiate(i: number) {
        this.currentPassword = i;

        this.input = "";
        const lock = core.createPrefab(lockPrefab);
        const container = getGameObjectById("Container");
        container.addChild(lock);

        const screen = core.createPrefab(screenPrefab);
        this.textRenderer = getGameObjectById("screenPrefab").getScript(TextRenderer);
        container.addChild(screen);

        const numObjs = lock.children;
        for (var i = 0; i < numObjs.length; i++) {
            const hitTest = numObjs[i].getScript(HitTestScript);
            this.buttons[i] = new Button(i + 1, hitTest);
        }

        this.checkHitTest();
    }

    private checkHitTest() {
        const lockPrefab = getGameObjectById("lockPrefab");
        const hitTest = lockPrefab.getScript(HitTestScript);
        hitTest.onClick = () => {
            console.log("我可以被点击到，我是lock");
        }
    }

    public check() {

        if (this.input == this.passwords[this.currentPassword]) {
            this.pass();
        } else {
            this.failed();
            this.input = "";
        }


        this.lockDestory();
    }

    public lockDestory() {
        const container = getGameObjectById("Container");
        container.removeChild(getGameObjectById("screenPrefab"));
        container.removeChild(getGameObjectById("lockPrefab"));
        console.log(getGameObjectById("screenPrefab"));
    }
}

class Button {
    private num: number;
    private hitTest: HitTestScript;

    constructor(num: number, hitTest: HitTestScript) {
        this.num = num;
        this.hitTest = hitTest;
        this.setListener();
    }

    setListener() {
        this.hitTest.onClick = () => {
            lock.input += this.num;
            lock.textRenderer.text = lock.input;
            console.log(lock.input);

            if (lock.input.length >= 4) {
                lock.check();
            }
        }
    }
}

export const lock = new Lock();